package com.nbb.aop;

import com.alibaba.dubbo.rpc.RpcContext;
import common.util.GuuidUtil;
import common.util.web.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class CommenWebFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CommenWebFilter.class);



    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        // 传递logId
        String logId = GuuidUtil.getUuid();
        RpcContext.getContext().setAttachment("logId", logId);
        String msg = "Timing filter ip : {},url : {},logId : {},spentMs : {}";
        long t1 = System.currentTimeMillis();
        beforeCreaterMDC(logId,req);
        chain.doFilter(request, response);
        long t2 = System.currentTimeMillis();
        long spentMs = t2-t1;

        String reqIp = RequestUtils.getIP(req);
        String reqUrl = req.getRequestURI();
        logger.info(String.format(msg,reqIp,reqUrl,logId,spentMs));
        if (spentMs > 500 && spentMs < 5000 ) {
            //logger.warn(msg,reqIp,reqUrl,logId,spentMs);
        }else if(spentMs >= 5000 ){
            //logger.error(msg,reqIp,reqUrl,logId,spentMs);
            //logToEmail.timingFilterLogToEmail(msg,reqIp,reqUrl,logId,spentMs);
        }
        //清空MDC中的值
        removeMDC();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void beforeCreaterMDC(String logId, HttpServletRequest request) {
        try {
            MDC.put("logId", logId);
            MDC.put("ipAddress", RequestUtils.getIP(request));
            MDC.put("url", request.getRequestURL().toString());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void removeMDC() {
        MDC.remove("logId");
        MDC.remove("ipAddress");
        MDC.remove("url");
    }
}
